package com.xzp.blog.controller;

import com.xzp.blog.controller.base.BaseController;
import com.xzp.blog.entity.Admin;
import com.xzp.blog.entity.dto.form.UserLoginForm;
import com.xzp.blog.service.IAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;

import static com.xzp.blog.consts.Message.USER_PASS_ERROR;
import static com.xzp.blog.consts.ViewConsts.VIEW_MSG;

/**
 * 后台登陆验证控制器
 */
@Controller
@RequestMapping("/adminlogin")
public class AdminLoginController extends BaseController {


    @Autowired
    private IAdminService adminService;

    /**
     * 后台登录跳转
     * @return
     */
    @GetMapping({"","/index"})
    public String adminLogin(){
        return "admin/userlogin";
    }


    @PostMapping("/login.f")
    public String adminLoginCheck(@Valid UserLoginForm userLoginForm, BindingResult bindingResult, HttpServletRequest request, Model model) throws Exception {
        if (bindingResult.hasErrors()){
            List<ObjectError> errors = bindingResult.getAllErrors();
            return "redirect:/adminlogin?msg="+ errors.get(0).getDefaultMessage();
        }

        Admin admin = adminService.adminLoginCheck(userLoginForm);
        if (admin != null){
            adminService.joinSession(request,admin);
            return "redirect:/admin/index";
        }

//        return  "admin/userlogin";
//        return "redirect:/adminlogin?msg=login error";
        addModelAtt(model,VIEW_MSG,USER_PASS_ERROR);
        return "admin/userlogin";
    }





}
